import { asyncRoutes, constantRoutes } from '@/router';
import { getMenus } from '@/api/menu';
import request from "@/utils/request";  // 获取菜单数据的API

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  }
};
export function listAnnouncement(query) {
  return request({
    url: '/announcement/announcement/list',
    method: 'get',
    params: query
  })
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getMenus().then(response => {
        const accessedRoutes = filterAsyncRoutes(response.data);
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes);
      }).catch(error => {
        reject(error);
      });
    });
  }
};

function filterAsyncRoutes(routes) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children);
    }
    res.push(tmp);
  });
  return res;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
